package dormouse.vfs.task;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.common.collect.Multimap;

/**
 * This factory serves as a registry for available file tasks.
 * 
 */
public class FileTaskFactory {

	/**
	 * A list of tasks that can be used with any file type regardless of the
	 * extension.
	 */
	List<IFileTask> allFileTasks = null;

	/** A map of tasks that can only be used by files of a given extension. */
	Multimap<String, IFileTask> extTaskMap = null;

	/**
	 * This method gets a list of all tasks for a given file extension.
	 * 
	 * @param ext
	 *            the file extension
	 */
	public List<IFileTask> getFileTasks(String ext) {
		List<IFileTask> taskList = new ArrayList<IFileTask>();
		taskList.addAll(allFileTasks);

		Collection<IFileTask> tasks = extTaskMap.get(ext);
		if (tasks != null && !tasks.isEmpty()) {
			taskList.addAll(tasks);
		}

		return taskList;
	}

	/**
	 * This method registers a task with the factory.
	 * 
	 * @param task the task to be added.
	 */
	public void add(IFileTask task) {
		String[] exts = task.getFileExtensions();
		if (exts == null) {
			allFileTasks.add(task);
		} else {
			for (String ext : exts) {
				extTaskMap.put(ext, task);
			}
		}
	}

}
